/**
 * 关系计算工具类
 * 用于复用天干地支关系计算逻辑
 */

import { 
    isTianganChong, 
    isTianganKe, 
    isTianganHe,
    isDizhiLiuhe,
    isDizhiSanhe,
    isDizhiSanhui,
    isDizhiAnhe,
    isDizhiXing,
    isDizhiChong,
    isDizhiPo,
    isDizhiHai,
    isGaitou,
    isJiejiao,
    isDizhiBanhe,
    isDizhiGongSanhui,
    isDizhiAnheJu,
    isDizhiGonghe,
    isDizhiAnSanhui,
    isDizhiSiheTu,
    getTianganHehua,
    getDizhiLiuheHuahua,
    getDizhiSanheHuahua,
    getDizhiSanhuiHuahua
} from '@/utils/ganzhi-relations'

interface Pillar {
    gan: string
    zhi: string
}

/**
 * 格式化关系显示文本（至少四个字）
 */
export const formatRelationText = (
    type: string, 
    pair: string, 
    gan1?: string, 
    gan2?: string, 
    zhi1?: string, 
    zhi2?: string, 
    zhi3?: string
): string => {
    // 相克关系：显示"甲乙相克"格式（至少四个字）
    if (type.includes('克')) {
        // type 是 "甲克乙" 格式，需要转换成 "甲乙相克" 格式
        const match = type.match(/^(.+)克(.+)$/)
        if (match) {
            const [, gan1, gan2] = match
            return `${gan1}${gan2}相克`
        }
        // 如果 match 失败，使用 pair 构建至少四个字的文本
        return `${pair}相克`
    }
    
    // 相冲关系：显示"xx相冲"格式
    if (type === '相冲') {
        return `${pair}相冲`
    }
    
    // 天干五合：显示"甲己合化土"格式
    if (type === '五合' && gan1 && gan2) {
        const huahua = getTianganHehua(gan1, gan2)
        if (huahua) {
            return `${pair}合化${huahua}`
        }
        return `${pair}五合`
    }
    
    // 地支六合：显示"子丑合化土"格式
    if (type === '六合' && zhi1 && zhi2) {
        const huahua = getDizhiLiuheHuahua(zhi1, zhi2)
        if (huahua) {
            return `${pair}合化${huahua}`
        }
        return `${pair}六合`
    }
    
    // 地支三合：显示"申子辰三合水局"格式
    if (type === '三合' && zhi1 && zhi2 && zhi3) {
        const huahua = getDizhiSanheHuahua(zhi1, zhi2, zhi3)
        if (huahua) {
            return `${pair}三合${huahua}局`
        }
        return `${pair}三合`
    }
    
    // 地支三会：显示"寅卯辰三会木局"格式
    if (type === '三会' && zhi1 && zhi2 && zhi3) {
        const huahua = getDizhiSanhuiHuahua(zhi1, zhi2, zhi3)
        if (huahua) {
            return `${pair}三会${huahua}局`
        }
        return `${pair}三会`
    }
    
    // 地支半合：显示"申子半合水局"格式
    if (type === '半合' && zhi1 && zhi2) {
        const banhe = isDizhiBanhe(zhi1, zhi2)
        if (banhe.isBanhe && banhe.huahua) {
            return `${pair}半合${banhe.huahua}局`
        }
        return `${pair}半合`
    }
    
    // 地支关系：显示"子丑相冲"等格式
    const relationMap: Record<string, string> = {
        '相冲': '相冲',
        '相刑': '相刑',
        '相破': '相破',
        '相害': '相害',
        '暗合': '暗合',
        '暗合局': '暗合局',
        '暗三会局': '暗三会局',
        '拱合': '拱合',
        '拱三会': '拱三会',
        '四合土局': '四合土局'
    }
    
    const suffix = relationMap[type] || type
    return `${pair}${suffix}`
}

/**
 * 计算天干关系
 */
export const calculateTianganRelations = (pillars: Pillar[]): string[] => {
    if (pillars.length === 0) return []
    const relations: string[] = []
    const handled = new Set<string>()
    
    for (let i = 0; i < pillars.length; i++) {
        for (let j = i + 1; j < pillars.length; j++) {
            const pillar1 = pillars[i]
            const pillar2 = pillars[j]
            if (!pillar1 || !pillar2) continue
            
            const gan1 = pillar1.gan
            const gan2 = pillar2.gan
            if (!gan1 || !gan2) continue
            
            const key = `${gan1}-${gan2}`
            const relationTypes: string[] = []
            
            // 检测所有可能的关系（允许同时存在多种关系）
            if (isTianganChong(gan1, gan2)) {
                relationTypes.push('相冲')
            }
            if (isTianganHe(gan1, gan2)) {
                relationTypes.push('五合')
            }
            if (isTianganKe(gan1, gan2)) {
                relationTypes.push(`${gan1}克${gan2}`)
            }
            if (isTianganKe(gan2, gan1)) {
                relationTypes.push(`${gan2}克${gan1}`)
            }
            
            // 添加所有检测到的关系
            relationTypes.forEach((relType) => {
                const uniqueKey = `${key}-${relType}`
                if (!handled.has(uniqueKey)) {
                    const pair = `${gan1}${gan2}`
                    // 对于五合，传递天干参数以获取合化信息
                    if (relType === '五合') {
                        relations.push(formatRelationText(relType, pair, gan1, gan2))
                    } else {
                        relations.push(formatRelationText(relType, pair))
                    }
                    handled.add(uniqueKey)
                }
            })
        }
    }
    
    return relations
}

/**
 * 计算地支关系
 */
export const calculateDizhiRelations = (pillars: Pillar[]): string[] => {
    if (pillars.length === 0) return []
    const relations: string[] = []
    const handled = new Set<string>()
    const zhilist = pillars.map(p => p.zhi).filter(Boolean) as string[]
    const ganlist = pillars.map(p => p.gan).filter((gan): gan is string => !!gan)
    
    // 两两地支关系（按优先级顺序检测，但需要检测所有关系类型）
    for (let i = 0; i < zhilist.length; i++) {
        for (let j = i + 1; j < zhilist.length; j++) {
            const zhi1 = zhilist[i]
            const zhi2 = zhilist[j]
            if (!zhi1 || !zhi2) continue
            
            const key = `${zhi1}-${zhi2}`
            const relationTypes: string[] = []
            
            // 检测所有可能的关系（按优先级，允许同时存在多种关系）
            // 先检测半合（因为半合是两个地支，需要优先检测，避免被三合覆盖）
            const banhe = isDizhiBanhe(zhi1, zhi2)
            if (banhe.isBanhe) {
                relationTypes.push('半合')
            }
            
            // 检测暗合局（暗三合）- 需要天干配合，优先检测
            const anheJu = isDizhiAnheJu(zhi1, zhi2, ganlist)
            if (anheJu.isAnheJu) {
                relationTypes.push('暗合局')
            }
            
            // 检测暗三会局 - 需要天干配合，优先检测
            const anSanhui = isDizhiAnSanhui(zhi1, zhi2, ganlist)
            if (anSanhui.isAnSanhui) {
                relationTypes.push('暗三会局')
            }
            
            // 检测拱合局（拱三合）- 如果暗合局不满足，才检测拱合
            if (!anheJu.isAnheJu) {
                const gonghe = isDizhiGonghe(zhi1, zhi2)
                if (gonghe.isGonghe) {
                    relationTypes.push('拱合')
                }
            }
            
            // 检测拱三会（三会局缺少中间地支）- 暗三会局和拱三会可以同时显示
            const gongSanhui = isDizhiGongSanhui(zhi1, zhi2)
            if (gongSanhui.isGongSanhui) {
                relationTypes.push('拱三会')
            }
            
            if (isDizhiLiuhe(zhi1, zhi2)) {
                relationTypes.push('六合')
            }
            if (isDizhiChong(zhi1, zhi2)) {
                relationTypes.push('相冲')
            }
            if (isDizhiPo(zhi1, zhi2)) {
                relationTypes.push('相破')
            }
            if (isDizhiHai(zhi1, zhi2)) {
                relationTypes.push('相害')
            }
            if (isDizhiAnhe(zhi1, zhi2)) {
                relationTypes.push('暗合')
            }
            // 相刑检测（包括自刑：辰辰、午午、酉酉、亥亥）
            if (isDizhiXing(zhi1, zhi2)) {
                relationTypes.push('相刑')
            }
            
            // 添加所有检测到的关系（不再使用 else if，允许一个地支对存在多种关系）
            relationTypes.forEach((relType) => {
                const uniqueKey = `${key}-${relType}`
                if (!handled.has(uniqueKey)) {
                    const pair = `${zhi1}${zhi2}`
                    // 对于六合和半合，传递地支参数以获取合化信息
                    if (relType === '六合' || relType === '半合') {
                        relations.push(formatRelationText(relType, pair, undefined, undefined, zhi1, zhi2))
                    } else {
                        relations.push(formatRelationText(relType, pair))
                    }
                    handled.add(uniqueKey)
                }
            })
        }
    }
    
    // 三合、三会关系
    for (let i = 0; i < zhilist.length; i++) {
        for (let j = i + 1; j < zhilist.length; j++) {
            for (let k = j + 1; k < zhilist.length; k++) {
                const zhi1 = zhilist[i]
                const zhi2 = zhilist[j]
                const zhi3 = zhilist[k]
                if (!zhi1 || !zhi2 || !zhi3) continue
                
                const key = [zhi1, zhi2, zhi3].sort().join('-')
                
                if (handled.has(key)) continue
                
                if (isDizhiSanhe(zhi1, zhi2, zhi3)) {
                    const pair = `${zhi1}${zhi2}${zhi3}`
                    relations.push(formatRelationText('三合', pair, undefined, undefined, zhi1, zhi2, zhi3))
                    handled.add(key)
                } else if (isDizhiSanhui(zhi1, zhi2, zhi3)) {
                    const pair = `${zhi1}${zhi2}${zhi3}`
                    relations.push(formatRelationText('三会', pair, undefined, undefined, zhi1, zhi2, zhi3))
                    handled.add(key)
                }
            }
        }
    }
    
    // 四地支合土局（丑_辰_未_戌合土局）
    if (zhilist.length === 4) {
        const zhi1 = zhilist[0]
        const zhi2 = zhilist[1]
        const zhi3 = zhilist[2]
        const zhi4 = zhilist[3]
        if (zhi1 && zhi2 && zhi3 && zhi4) {
            if (isDizhiSiheTu(zhi1, zhi2, zhi3, zhi4)) {
                const key = [zhi1, zhi2, zhi3, zhi4].sort().join('-')
                if (!handled.has(key)) {
                    relations.push(`${zhi1}${zhi2}${zhi3}${zhi4}四合土局`)
                    handled.add(key)
                }
            }
        }
    }
    
    return relations
}

/**
 * 计算单柱关系（盖头、截脚）
 */
export const calculateSinglePillarRelations = (pillars: Pillar[]): string[] => {
    if (pillars.length === 0) return []
    const relations: string[] = []
    
    // 单柱关系（盖头、截脚）
    pillars.forEach((pillar) => {
        const { gan, zhi } = pillar
        if (!gan || !zhi) return
        
        if (isGaitou(gan, zhi)) {
            relations.push(`${gan}${zhi}盖头`)
        }
        if (isJiejiao(gan, zhi)) {
            relations.push(`${gan}${zhi}截脚`)
        }
    })
    
    return relations
}

/**
 * 计算两两柱之间的关系（伏吟、反吟）
 */
export const calculatePillarPairRelations = (pillars: Pillar[]): string[] => {
    if (pillars.length === 0) return []
    const relations: string[] = []
    const handled = new Set<string>()
    
    // 两两柱之间的关系（伏吟、反吟）
    for (let i = 0; i < pillars.length; i++) {
        for (let j = i + 1; j < pillars.length; j++) {
            const pillar1 = pillars[i]
            const pillar2 = pillars[j]
            if (!pillar1 || !pillar2) continue
            
            const gan1 = pillar1.gan
            const gan2 = pillar2.gan
            const zhi1 = pillar1.zhi
            const zhi2 = pillar2.zhi
            
            if (!gan1 || !gan2 || !zhi1 || !zhi2) continue
            
            const pair = `${gan1}${zhi1}${gan2}${zhi2}`
            const key = `${gan1}${zhi1}-${gan2}${zhi2}`
            
            // 检测伏吟：整柱相同（天干相同且地支相同）
            if (gan1 === gan2 && zhi1 === zhi2) {
                const uniqueKey = `${key}-伏吟`
                if (!handled.has(uniqueKey)) {
                    // 伏吟显示格式：只显示一次柱名，如"乙巳伏吟"
                    relations.push(`${gan1}${zhi1}伏吟`)
                    handled.add(uniqueKey)
                }
            }
            
            // 检测反吟：天克地冲（天干相冲且地支相冲）
            if (isTianganChong(gan1, gan2) && isDizhiChong(zhi1, zhi2)) {
                const uniqueKey = `${key}-反吟`
                if (!handled.has(uniqueKey)) {
                    relations.push(`${gan1}${zhi1}${gan2}${zhi2}反吟`)
                    handled.add(uniqueKey)
                }
            }
        }
    }
    
    return relations
}

/**
 * 计算整柱关系（盖头、截脚、伏吟、反吟）
 */
export const calculateZhengzhuRelations = (pillars: Pillar[]): string[] => {
    if (pillars.length === 0) return []
    const relations: string[] = []
    
    // 单柱关系（盖头、截脚）
    relations.push(...calculateSinglePillarRelations(pillars))
    
    // 两两柱之间的关系（伏吟、反吟）
    relations.push(...calculatePillarPairRelations(pillars))
    
    return relations
}

